package jst.householdmanager.activities;

import java.util.ArrayList;
import java.util.List;

import jst.householdmanager.GlobalFunc;
import jst.householdmanager.R;
import jst.householdmanager.activities.EditPurchaseListPosAct.EditPurchaseListAction;
import jst.householdmanager.database.ItemCategoriesDataSource;
import jst.householdmanager.database.ItemsDataSource;
import jst.householdmanager.database.Items_in_ItemCategoriesDataSource;
import jst.householdmanager.database.ShopsDataSource;
import jst.householdmanager.database.Shops_has_ItemsDataSource;
import jst.householdmanager.database.table.ItemCategories;
import jst.householdmanager.database.table.Items;
import jst.householdmanager.database.table.Shops;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

public class ItemListAct extends Activity {
	public enum ItemListAction {
		EDIT_ITEM, ADD_PURCHASE;
	}

	private static final int EDIT_ITEM_ACT_EDIT = 2000;
	private static final int EDIT_PURLISTPOS_ACT_EDIT = 3000;

	private List<Integer> itemCatspinnerIdList = new ArrayList<Integer>();
	private List<Integer> shopspinnerIdList = new ArrayList<Integer>();
	private ArrayList<ListEntryMultiline.EntryRecord> items;
	private ItemListAction itemListAction;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_itemlist);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		Bundle givenData = getIntent().getExtras();

		if (givenData != null) {
			this.itemListAction = (ItemListAction) givenData.get("ActionId");
		} else {
			this.itemListAction = ItemListAction.EDIT_ITEM;
		}

		switch (this.itemListAction) {
		case EDIT_ITEM:
			setTitle(R.string.items);
			break;
		case ADD_PURCHASE:
			setTitle(R.string.fill_purchaselist);
			break;
		}

		EditText itemlist_search = ((EditText) findViewById(R.id.itemlist_search));
		itemlist_search.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				ItemListAct.this.loadItemList();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		// fill spinners
		this.fillSpinners();

		ListView itemlist_list = (ListView) findViewById(R.id.itemlist_list);
		itemlist_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				Intent intent;
				switch (ItemListAct.this.itemListAction) {
				case EDIT_ITEM:
					intent = new Intent(ItemListAct.this, EditItemAct.class);
					intent.putExtra("ItemId", ItemListAct.this.items.get(position).id);
					startActivityForResult(intent, EDIT_ITEM_ACT_EDIT);
					break;
				case ADD_PURCHASE:
					intent = new Intent(ItemListAct.this, EditPurchaseListPosAct.class);
					intent.putExtra("ItemId", ItemListAct.this.items.get(position).id);
					intent.putExtra("FinDate", GlobalFunc.StringToDate("0000-00-00"));
					intent.putExtra("ActionId", EditPurchaseListAction.ADD_PURCHASE);
					startActivityForResult(intent, EDIT_PURLISTPOS_ACT_EDIT);
					break;
				}
			}
		});

		itemlist_list.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				AlertDialog.Builder builder = new AlertDialog.Builder(ItemListAct.this);
				final int itemId = ItemListAct.this.items.get(position).id;
				builder.setTitle(getText(R.string.selection));
				builder.setItems(new CharSequence[] { getText(R.string.edit), getText(R.string.add_to_purchaselist), getText(R.string.delete) },
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								switch (item) {
								case 0:
									Intent intent = new Intent(ItemListAct.this, EditItemAct.class);
									intent.putExtra("ItemId", itemId);
									startActivityForResult(intent, EDIT_ITEM_ACT_EDIT);
									break;
								case 1:
									intent = new Intent(ItemListAct.this, EditPurchaseListPosAct.class);
									intent.putExtra("ItemId", itemId);
									intent.putExtra("FinDate", GlobalFunc.StringToDate("0000-00-00"));
									intent.putExtra("ActionId", EditPurchaseListAction.ADD_PURCHASE);
									startActivityForResult(intent, EDIT_PURLISTPOS_ACT_EDIT);
									break;
								case 2:
									ItemListAct.this.deleteItem(itemId);
									break;
								}
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				return false;
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.list_action, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		case R.id.mnu_create:
			Intent intent = new Intent(ItemListAct.this, EditItemAct.class);
			startActivityForResult(intent, EDIT_ITEM_ACT_EDIT);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == EDIT_ITEM_ACT_EDIT) {
			Bundle resultBundle = data.getExtras();
			if (resultBundle.getBoolean("dataChanged")) {
				this.loadItemList();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void fillSpinners() {
		// fill ItemCategories spinner element
		List<String> itemCategoriesName = new ArrayList<String>();
		itemCategoriesName.add(getText(R.string.all).toString());
		this.itemCatspinnerIdList.add(0);

		List<ItemCategories> itemCategories = ItemCategoriesDataSource.readAll();

		for (ItemCategories itemCategory : itemCategories) {
			itemCategoriesName.add(itemCategory.getName());
			this.itemCatspinnerIdList.add(itemCategory.getId());
		}
		Spinner spin_ItemCategories = (Spinner) findViewById(R.id.itemlist_spinner_itemcategory);
		ArrayAdapter<String> itemCategoriesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemCategoriesName);
		spin_ItemCategories.setAdapter(itemCategoriesAdapter);

		spin_ItemCategories.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				ItemListAct.this.loadItemList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				return;
			}
		});

		// fill Shop spinner element
		List<String> shopName = new ArrayList<String>();
		shopName.add(getText(R.string.all).toString());
		this.shopspinnerIdList.add(0);

		List<Shops> shops = ShopsDataSource.readAll();

		for (Shops shop : shops) {
			shopName.add(shop.getName());
			this.shopspinnerIdList.add(shop.getId());
		}
		Spinner spin_Shops = (Spinner) findViewById(R.id.itemlist_spinner_shop);
		ArrayAdapter<String> shopsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, shopName);
		spin_Shops.setAdapter(shopsAdapter);

		spin_Shops.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				ItemListAct.this.loadItemList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				return;
			}
		});
	}

	private void loadItemList() {
		int itemCategoryId = ItemListAct.this.itemCatspinnerIdList.get(((Spinner) findViewById(R.id.itemlist_spinner_itemcategory))
				.getSelectedItemPosition());
		int shopId = ItemListAct.this.shopspinnerIdList.get(((Spinner) findViewById(R.id.itemlist_spinner_shop)).getSelectedItemPosition());

		ListEntryMultiline listEntryMultiline = new ListEntryMultiline(this);
		this.items = new ArrayList<ListEntryMultiline.EntryRecord>();

		String searchText = ((EditText) findViewById(R.id.itemlist_search)).getText().toString();

		for (Items item : ItemsDataSource.readAll()) {
			Boolean selectionOk = true;
			// selection ItemCategorie
			if ((itemCategoryId != 0) && (Items_in_ItemCategoriesDataSource.read(itemCategoryId, item.getId()) == null)) {
				selectionOk = false;
			}
			// selection Shop
			if (selectionOk && (shopId != 0) && (Shops_has_ItemsDataSource.read(shopId, item.getId()) == null)) {
				selectionOk = false;
			}
			// search text
			if (selectionOk) {
				if (GlobalFunc.Like(item.getName(), "%" + searchText + "%")) {
					this.items.add(listEntryMultiline.Record(item.getId(), item.getName(), item.getDescription()));
				}
			}
		}

		ListView itemList = (ListView) findViewById(R.id.itemlist_list);
		itemList.setAdapter(listEntryMultiline.Adapter(this, android.R.layout.simple_list_item_1, this.items));
	}

	private void deleteItem(final int itemId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getText(R.string.are_you_sure));
		builder.setMessage(getText(R.string.delete_item));
		// yes
		builder.setPositiveButton(getText(R.string.yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// delete items in ItemCategories
				Items_in_ItemCategoriesDataSource.delete(Items_in_ItemCategoriesDataSource.COLUMN_ITEM_ID, itemId);
				// delete items in Shops
				Shops_has_ItemsDataSource.delete(Shops_has_ItemsDataSource.COLUMN_ITEM_ID, itemId);
				ItemsDataSource.delete(new Items(itemId));
				ItemListAct.this.loadItemList();
				dialog.dismiss();
			}
		});
		// no
		builder.setNegativeButton(getText(R.string.no), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

}
